--
-- @Author:      feilong
-- @DateTime:    2019-12-11 23:05:48
-- @Description: 消息的处理


local mysql = require "skynet.db.mysql"

local M = class("Worker")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function M:ctor(conf_name)
    conf_name = conf_name or "mysql"
    local server_config = g.getServerConf()
    local conf = server_config[conf_name]
    self.db_info = {
        host = conf.host,
        port = conf.port,
        database = conf.database,
        user = conf.user,
        password = conf.password,
    }
    g.log:debug("mysql_db_info: ", self.db_info)
    self.conn = nil --连接

    self:register()
    -- self:connect()
end

--注册本服务里的消息
function M:register()
    g.dispatch:registerDefault(handler(self, self.normalCommand))
end

--从连接池里取一个服务
function M:getConnect()    
    if self.conn then        
        return self.conn
    end
    local ok, ret = xpcall(mysql.connect, debug.traceback, self.db_info)
    while not ok do
        g.log:error('failed to connect mysql',ret)
        g.sleep(500) --one second
        ok, ret = xpcall(mysql.connect, debug.traceback, self.db_info)
    end
    self.conn = ret
    return ret
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------
--处理请求
function M:normalCommand(sql, ...)
    local conn = self:getConnect()
    if not conn then
        g.log:err("normalCommand", sql, ...)
    end
    --g.log:warn("normalCommand", sql, ...)
    local func = conn["query"]
    local ok, ret = xpcall(func, debug.traceback, conn, sql, ...)
    while not ok do
        print('mysql execute err now retry ....', tostring(self.db_info), sql, ...)
        g.sleep(300)
        ok, ret = xpcall(func, debug.traceback, conn, sql, ...)
    end
    if not ok then
        g.log:error(ret)
    end
    if ret and type(ret)=="table" and ret.err then
        g.log:err("normalCommand:", ..., ok, ret, sql)
    end

    return ret
end





return M

